package com.huizu.project.service.impl;

import java.io.*;
import java.rmi.ServerException;
import java.util.Date;
import java.util.List;

import com.huizu.common.core.domain.AjaxResult;
import com.huizu.common.exception.ServiceException;
import com.huizu.common.utils.DateUtils;
import com.huizu.common.utils.SnowFlake;
import com.huizu.common.utils.poi.ExcelUtil;
import com.huizu.project.domain.ProUser;
import com.huizu.project.domain.TheoryScoreExcelVo;
import com.huizu.project.domain.TheoryScoreVo;
import com.huizu.project.mapper.ProUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huizu.project.mapper.ProUserLlPointsMapper;
import com.huizu.project.domain.ProUserLlPoints;
import com.huizu.project.service.IProUserLlPointsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 理论成绩Service业务层处理
 * 
 * @author pjl
 * @date 2024-09-04
 */
@Service
public class ProUserLlPointsServiceImpl implements IProUserLlPointsService {
    @Autowired
    private ProUserLlPointsMapper proUserLlPointsMapper;

    @Autowired
    private ProUserMapper proUserMapper;


    /**
     * 查询理论成绩
     * 
     * @param id 理论成绩主键
     * @return 理论成绩
     */
    @Override
    public ProUserLlPoints selectProUserLlPointsById(String id)
    {
        return proUserLlPointsMapper.selectProUserLlPointsById(id);
    }

    /**
     * 查询理论成绩列表
     * 
     * @param proUserLlPoints 理论成绩
     * @return 理论成绩
     */
    @Override
    public List<ProUserLlPoints> selectProUserLlPointsList(ProUserLlPoints proUserLlPoints)
    {
        return proUserLlPointsMapper.selectProUserLlPointsList(proUserLlPoints);
    }

    /**
     * 新增理论成绩
     * 
     * @param proUserLlPoints 理论成绩
     * @return 结果
     */
    @Override
    public int insertProUserLlPoints(ProUserLlPoints proUserLlPoints)
    {
        proUserLlPoints.setCreateTime(DateUtils.getNowDate());
        return proUserLlPointsMapper.insertProUserLlPoints(proUserLlPoints);
    }

    /**
     * 修改理论成绩
     * 
     * @param proUserLlPoints 理论成绩
     * @return 结果
     */
    @Override
    public int updateProUserLlPoints(ProUserLlPoints proUserLlPoints)
    {
        return proUserLlPointsMapper.updateProUserLlPoints(proUserLlPoints);
    }

    /**
     * 批量删除理论成绩
     * 
     * @param ids 需要删除的理论成绩主键
     * @return 结果
     */
    @Override
    public int deleteProUserLlPointsByIds(String[] ids)
    {
        return proUserLlPointsMapper.deleteProUserLlPointsByIds(ids);
    }

    /**
     * 删除理论成绩信息
     * 
     * @param id 理论成绩主键
     * @return 结果
     */
    @Override
    public int deleteProUserLlPointsById(String id)
    {
        return proUserLlPointsMapper.deleteProUserLlPointsById(id);
    }

    @Override
    public List<TheoryScoreVo> selectForList(TheoryScoreVo theoryScoreVo) {
        String studentName = theoryScoreVo.getStudentName();
        String studentNumber = theoryScoreVo.getStudentNumber();
        String clId = theoryScoreVo.getClId();
        return proUserLlPointsMapper.selectForList(studentName,studentNumber,clId,theoryScoreVo.getXyId(),theoryScoreVo.getNjId(),theoryScoreVo.getZyId(),theoryScoreVo.getBjIds());
    }

    @Override
    public void download(HttpServletRequest request, HttpServletResponse response, String filePath) throws IOException {
        // 检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
            throw new ServerException("文件不存在");
        }

        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

        // 创建输入流和输出流
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;

            // 读取文件并写入响应输出流
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        }
    }

    @Override
    @Transactional
    public void importTheoryScore(MultipartFile file) throws Exception {
        ExcelUtil<TheoryScoreExcelVo> theoryScoreVoExcelUtil = new ExcelUtil<>(TheoryScoreExcelVo.class);
        List<TheoryScoreExcelVo> theoryScoreVos = theoryScoreVoExcelUtil.importExcel(file.getInputStream());
        for (TheoryScoreExcelVo theoryScoreExcelVo : theoryScoreVos) {
            if (StringUtils.isEmpty(theoryScoreExcelVo.getStudentNumber())) {
                throw new ServiceException("学生编号不能为空");
            }

            if (theoryScoreExcelVo.getPoints() == null) {
                throw new ServiceException("理论成绩不能为空");
            }

            ProUserLlPoints points = new ProUserLlPoints();
            points.setPoints(theoryScoreExcelVo.getPoints());

            // 查询学生信息
            ProUser proUser = proUserMapper.selectProUserByStNumber(theoryScoreExcelVo.getStudentNumber());
            if (proUser == null) {
                throw new ServiceException("未找到" + theoryScoreExcelVo.getStudentName() + "学生");
            }

            //查询此学生理论成绩信息
            points.setUserId(proUser.getUserId());
            ProUserLlPoints proUserLlPoints = proUserLlPointsMapper.selectProUserLlPointsByUserId(proUser.getUserId());

            // 判断是否需要更新成绩
            if (proUserLlPoints != null) {
                proUserLlPoints.setPoints(theoryScoreExcelVo.getPoints());
                int row = proUserLlPointsMapper.updateProUserLlPoints(proUserLlPoints);
                if (0 == row) {
                    throw new ServiceException("更新成绩失败");
                }
                continue;
            }

            points.setId(String.valueOf(SnowFlake.nextId()));
            points.setType("1");
            points.setCreateTime(new Date());
            int row = proUserLlPointsMapper.insertProUserLlPoints(points);
            if (0 == row) {
                throw new ServiceException("插入成绩失败");

            }
        }
    }

    @Override
    public void update(TheoryScoreVo theoryScoreVo) {
        ProUserLlPoints points = new ProUserLlPoints();
        points.setPoints(theoryScoreVo.getTheoryScore());
        points.setId(theoryScoreVo.getId());
        int row = proUserLlPointsMapper.updateProUserLlPoints(points);
        if (0 == row) {
            throw new ServiceException("更新成绩失败");
        }
    }
}
